var wfId = RequestURLParam.getParam("wfId"),
    wfaId = RequestURLParam.getParam("wfaId"),
    form,
    authtree,
    deactivate = [],//停用参数"juese","teshu","canyuzhe"
    valueMap = new Map();// 参与者Map<value, type>
/*
* 数据保存到valueMap里
* */
layui.config({
    base: '/static/lib/layuiadmin/',
}).extend({
    authtree_zimi: 'modules/authtree_zimi',
}).use(['table', 'jquery', 'form', 'layer', 'authtree_zimi'], function () {
    authtree = layui.authtree_zimi;
    form = layui.form;
    var layer = layui.layer;
    //初始化数据
    participator();//参与者
    RoleAuthority();//职务
    specialness();//特殊
    loadOrgSel("");//指定环节
});

userData(JSON.parse(parent.$("#arrAuths").val()));

/*
* wf_activity_authority表里的值 以类型-机构编号-对象编号为key，值为对象保存在全局变量的Map里
* */
function userData(authData) {
    // 清理valueMap
    valueMap.clear();

    $.each(authData, function (i, item) {
        valueMap.set(`${item.activityType}-${item.orgId ? item.orgId : "0"}-${item.role}`, item);
    });
};

/*
*参与者数据(机构/岗位/用户)
* */
function participator() {
    $.ajax({
        url: '/wf/activity/authority/userTree'
        , type: 'post'
        , success: function (res) {
            if (res.code == 0) {
                var trees = formatData(res.data, 'parentId', 'id', 'name', 'choiceFlag');
                authtree.render('#canyuzhe', trees, {
                    inputname: 'authids[]',
                    layfilter: 'lay-check-auth',
                    fgo: 0,
                    flags: [1, 3, 5],
                    checkedArr: res.checkedArr,
                    autowidth: true,
                });

                authtree.showDept('#canyuzhe', 2);
            } else {
                layer.msg(res.msg, {icon: 5, time: 1000});
            }
        }
    });
};

//角色权限
function RoleAuthority() {
    ActHttpRequest('/sys-role/allList', {}, function (res) {
        if (res.code === 0) {
            setRoleAuthorityData(res);
        } else {
            console.log(res.msg);
        }
    }, null, null, null, '保存中。。。', false);
};


function setRoleAuthorityData(data) {

    if (!data.List) return;
    if (data.List.length > 0) {
        //根据flag来进行图标转换
        // data.List.map(item => (item.flag == 4 ? 5 : 4));
        var obj = null;
        var list = [];
        var codeMap = new Map();

        data.List.forEach(function (item, index) {
            obj = new Object();
            obj.name = item.roleName;
            item.flag = 4;
            item.orgId = 0;
            obj.value = JSON.stringify(item).replace(/"/g, "'");
            obj.checked = valueMap.get(`${item.flag}-${item.orgId}-${item.id}`) == null ? false : true;
            list.push(obj);
        });

        //使用插件显示树形结构
        authtree.render('#juese', list, {
            inputname: 'ids[canyuzhe]'
            , layfilter: 'lay-check-auth'
            , fgo: 0
            // ,openall: true
            , checkType: 'checkbox'
            , autowidth: true,
            flags: [4]
        });

        authtree.showDept('#juese', 1);
    }
};


//特殊权限计算
function specialness() {
    ActHttpRequest('/sys-code/list', {
        'codeTypeName': 'liuchengcanyuzheteshuleibie',
        'codeIsParent': 2
    }, function (data) {
        if (data.OK == "OK") {
            setSpecialnessData(data);
        } else {
            console.log('Geat sysCode failed!');
        }
    }, null, null, null, '保存中。。。', false);
};

//封装特殊数据
function setSpecialnessData(data) {
    if (!data.List) return;
    if (data.List.length > 0) {
        var obj = null;
        var list = [];

        data.List.forEach(function (item, index) {
            obj = new Object();
            obj.name = item.codeName;
            item.flag = 6;
            item.orgId = 0;
            obj.value = JSON.stringify(item).replace(/"/g, "'");
            obj.checked = valueMap.get(`${item.flag}-${item.orgId}-${item.codeValue}`) == null ? false : true;
            list.push(obj);
        });

        //使用插件显示树形结构
        authtree.render('#teshu', list, {
            inputname: 'ids[canyuzhe]'
            , layfilter: 'lay-check-auth'
            , fgo: 0
            , checkType: 'checkbox'
            , autowidth: true
            , flags: [6]
        });

        authtree.showDept('#teshu', 1);
    }
};

//封装数据
function getvalue() {
    var lists = [],
        obj = null,
        value,
        appointActivity,
        strName

    //把数据拼接成字符串
    $('div.layui-form-checked').each(function (index, data) {
        obj = $(this).prev();
        value = eval("(" + obj["0"].value + ")");
        if (!value.checked) {

            obj = new Object();
            obj.activityId = parseInt(wfaId);
            obj.activityType = value.flag;
            obj.authType = getTypeName(value.flag)
            obj.orgId = value.orgId;
            obj.role = value.id;

            strName = value.name
            if (value.flag == 6) {
                strName = value.codeName
                obj.role = value.codeValue
            }
            if (value.flag == 4) strName = value.roleName
            if (value.flag == 3) {
                strName = value.orgName + " - " + value.name
            }

            obj.name = strName


            lists.push(obj);

        }
    });

    appointActivity = $("#activityId").find("option:selected");

    if (appointActivity.val()) {
        obj = new Object();
        obj.activityId = parseInt(wfaId);
        obj.orgId = 0;
        obj.activityType = 7;
        obj.authType = "指定环节办理人"
        obj.role = appointActivity.val();
        obj.name = appointActivity.text()
        lists.push(obj)
    }
    return lists;
}

/*
* 确定时选择的值保存到Div(arrAuths)的值
*/
function tijiao() {
    var reLists = getvalue();
    // console.log(reLists)
    parent.$("#arrAuths").val(JSON.stringify(reLists))
    closeMe();
    window.parent.window.tableAuthInit();
};

/*
* 树结构的元数据添加选择属性
* */
function checkedForData(data) {
    if (data.hasOwnProperty('list') && data.list.length > 0)
        Array.from(data.list).forEach(function (v, i) {
            v.checked = valueMap.get(v.value.toString()) == null ? false : true;
            checkedForData(v);
        });

};

function closeMe() {
    parent.layer.close(parent.$("#divTree").val())
};

// 显示到某层
function showDept(value) {
    var treeId = '#canyuzhe'
    authtree.showDept(treeId, 2);
};


//停用
function Disable(deactivate) {
    //传入参数禁用对应参数的数据
    deactivate.forEach(function (value, index) {
        if (value == "canyuzhe") {
            $("#" + value + " input[type='checkbox']").prop("disabled", "disabled");
        } else {
            if (value == "juese") {
                $("#" + value + " input[type='checkbox']").prop("disabled", "disabled");
            } else {
                if (value == "teshu") {
                    $("#" + value + " input[type='checkbox']").prop("disabled", "disabled");
                }
            }
        }
        form.render();
    })

};

/*
* @author: wj
* @description: 加载指定环节
* @date: 2019/3/12 16:38
* @param
* @return
*/
function loadOrgSel(checked) {
    ActHttpRequest("/wf/activity/listVO", {'wfId': wfId, 'curWfaId': wfaId}, function (data) {
        if (data.OK == "OK") {
            if (data.List && data.List.length > 0) {
                var html = "";
                for (var i = 0, j = data.List.length; i < j; i++) {
                    var obj = data.List[i];
                    if (obj.activityType === "end" || obj.activityType === "start") continue;

                    if (valueMap.get('7-0-' + obj.wfaId)) {
                        html += (`<option value="${obj.wfaId}" selected="">${obj.activityName}</option>`);
                    } else {
                        html += (`<option value="${obj.wfaId}">${obj.activityName}</option>`);
                    }
                }

                $("select[id='activityId']").append(html);
                form.render();
            }
        }
    });
}


function changeFlag(flag) {
    switch (flag) {
        case 0:
            flag = 1;
            break;
        case 1:
            flag = 2;
            break;
        case 5:
            flag = 4;
            break;
    }
    return flag;
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData(values, pid, id, name, checked) {
/*
    //转换flag
    values.map(item => {
        item.flag = changeFlag(item.flag);
    });
*/

    var tree = [],
        item,
        obj;

    var orgMap = new Map();
    var postMap = new Map();
    var userMap = new Map();
    var cateMap = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();

        obj = valueMap.get(`${values[i].flag}-${values[i].orgId}-${values[i].id}`)
        if (!obj && values[i].id) obj = valueMap.get(`${values[i].flag}-0-${values[i].id}`)

        if (obj) {
            values[i][checked] = true;
        }

        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.name = values[i][name];
        item.type = values[i].flag;
        item.checked = values[i][checked];
        item.list = [];

        switch (values[i].flag) {
            case 0:
                item.name = values[i].orgName;
                cateMap.set(values[i].orgId, item);
                tree.push(item);
                break;
            case 1:
                orgMap.set(values[i][id], item);
                break;
            case 3:
                postMap.set(values[i].orgId + '-' + values[i][id], item);
                break;
            case 5:
                userMap.set(values[i][id], item);
                break;
        }
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {
        switch (values[i].flag) {
            case 0:
                break;
            case 1:
                if (values[i][pid] > 0) {
                    obj = orgMap.get(values[i][pid]);
                } else {
                    obj = cateMap.get(values[i].orgCateId);
                }

                obj.list.push(orgMap.get(values[i][id]));

                break;
            case 3:
                obj = orgMap.get(values[i][pid]);
                obj.list.splice(obj.list.length - 1, 0, postMap.get(values[i].orgId + '-' + values[i][id]));
                break;
            case 5:
                obj = postMap.get(values[i].orgId + '-' + values[i].postId);

                if (obj) {
                    obj.list.push(userMap.get(values[i][id]));
                }
                break;
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < tree.length; i++) {
        removeChild(tree[i]);
    }

    return tree;
}

function removeChild(obj) {
    if (obj.hasOwnProperty('list')) {
        if (obj.list.length > 0) {
            if (obj.list.length == 1 && obj.type == 1) {
                delete obj.list;
            } else {
                for (var i = obj.list.length - 1; i >= 0; i--) {
                    removeChild(obj.list[i]);
                }
            }
        } else {
            delete obj.list;
        }
    }
}

function getTypeName(i) {
    var strRes = ""
    switch (i) {
        case 1:
            strRes = "机构";
            break;
        case 3:
            strRes = "岗位";
            break;
        case 4:
            strRes = "角色";
            break;
        case 5:
            strRes = "用户";
            break;
        case 6:
            strRes = "计算";
            break;
        case 7:
            strRes = "指定环节";
            break;
    }

    return strRes
}

function clearAll() {

    authtree.uncheckAll("#canyuzhe")
    authtree.uncheckAll("#teshu")
    authtree.uncheckAll("#juese")
}